import React, { Component, useState, useEffect } from 'react'
import ReactDom from 'react-dom'
//类式组件
class Demo_Class extends Component {
  state = { count: 0 }
  add = () => {
    this.setState(state => ({ count: state.count + 1 }))
  }
  // count值自增
  componentDidMount() {
    this.timer = setInterval(() => {
      this.setState(state => ({ count: state.count + 1 }))
    }, 1000)
  }

  // 卸载页面 清空定时器
  componentWillUnmount() {
    clearInterval(this.timer)
  }
  unMount = () => {
    ReactDom.unmountComponentAtNode(document.getElementById("root"))
  }

  render() {
    const { count } = this.state
    return (
      <div>
        <h1>当前计数:{count}</h1>
        <button onClick={this.add}>点击+1</button>
        <button onClick={this.unMount}>卸载页面</button>
      </div>
    )
  }
}

// 函数式组件

function Demo_Function() {
  // 让函数体 可以使用state 
  const [count, setCount] = useState(0)
  const [name, setName] = useState('jack')

  // 第一个回调函数的返回值,相当与willUnmount 生命周期
  // 第二个参数 传入空数组 相当与 didMount生命周期
  useEffect(() => {
    let timer = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)

    return () => {
      console.log('页面卸载了')
      clearInterval(timer)
    }
  }, [])
  function add() {
    setCount(count => {
      console.log(count)
      return count + 1
    })
  }
  function changeUser() {
    setName('Tom')
  }
  function unMount() {
    ReactDom.unmountComponentAtNode(document.getElementById("root"))
  }
  return (
    <div>
      <h1>当前计数:{count}</h1>
      <h2>当前用户姓名是:{name}</h2>
      <button onClick={add}>点击+1</button>
      <button onClick={changeUser}>切换用户</button>
      <button onClick={unMount}>卸载页面</button>
    </div>
  )
}


// export default Demo_Class
export default Demo_Function